<template>
	<div>
		<div class="head">
			<a @click="back()" class="return"></a>
			扫一扫
		</div>
		<div class="overlay">
			<div class="scan overlay-content">
				<div id="bcid">
				</div>
			</div>
		</div>
	</div>
</template>

<script>
	let scan = null;

	export default {
		data() {
			return {
				codeUrl: '',
			}
		},
		mounted() {
			this.startRecognize();
			this.startScan();
			var $this = this;
			plus.key.addEventListener("backbutton", function() {
				$this.cancelScan();
				$this.closeScan();
			});
		},
		methods: {
			// 创建扫描控件
			startRecognize() {
				let that = this;
				var height = window.innerHeight + 'px'; // 获取页面实际高度   
				var width = window.innerWidth + 'px';
				document.getElementById("bcid").style.height = height;
				document.getElementById("bcid").style.width = width;
				if(!window.plus) return;
				scan = new plus.barcode.Barcode('bcid',null, {
					frameColor: "#3d67ea"
				});
				scan.onmarked = onmarked;

				function onmarked(type, result, file) {
					switch(type) {
						case plus.barcode.QR:
							type = 'QR';
							break;
						case plus.barcode.EAN13:
							type = 'EAN13';
							break;
						case plus.barcode.EAN8:
							type = 'EAN8';
							break;
						default:
							type = '其它' + type;
							break;
					}
					result = result.replace(/\n/g, '');
					that.codeUrl = result;
					that.cancelScan();
					that.closeScan();
					localStorage.setItem('codeResult', result);
					that.$router.back(-1);
				}
			},
			// 开始扫描
			startScan() {
				if(!window.plus) return;
				scan.start();
			},
			// 关闭扫描
			cancelScan() {
				if(!window.plus) return;
				scan.cancel();
			},
			// 关闭条码识别控件
			closeScan() {
				if(!window.plus) return;
				scan.close();
			},
			back() {
				this.cancelScan();
				this.closeScan();
				this.$router.back(-1);
			}
		}
	}
</script>
<style scoped="scoped">
	#bcid {
		position: fixed;
		color: #00b07c;
	}
</style>